<template>
	<view class="user-edit">
		<!-- 基本信息 -->
		<view class="section">
			<view class="section-title">基本信息</view>
			<view class="form-item">
				<text class="label">用户名</text>
				<input class="input" v-model="userInfo.username" placeholder="请输入用户名" />
			</view>
			<view class="form-item">
				<text class="label">昵称</text>
				<input class="input" v-model="userInfo.nickname" placeholder="请输入昵称" />
			</view>
			<view class="form-item">
				<text class="label">手机号</text>
				<input class="input" type="number" v-model="userInfo.mobile" placeholder="请输入手机号" />
			</view>
			<view class="form-item">
				<text class="label">头像</text>
				<view class="upload-box" @click="chooseAvatar">
					<image v-if="userInfo.avatar" :src="userInfo.avatar" mode="aspectFill" class="preview-image"></image>
					<view v-else class="upload-placeholder">
						<text class="iconfont icon-camera"></text>
						<text>点击上传头像</text>
					</view>
				</view>
			</view>
		</view>
		
		<!-- 密码设置 -->
		<view class="section">
			<view class="section-title">密码设置</view>
			<view class="form-item">
				<text class="label">密码</text>
				<input class="input" type="password" v-model="userInfo.password" placeholder="请输入密码" />
			</view>
		</view>
		
		<!-- 提交按钮 -->
		<view class="submit-btn" @click="handleSubmit">保存</view>
	</view>
</template>

<script>
export default {
	data() {
		return {
			userId: '',
			userInfo: {
				username: '',
				nickname: '',
				mobile: '',
				avatar: '',
				password: ''
			}
		}
	},
	onLoad(options) {
		if (options.id) {
			this.userId = options.id
			this.loadUserDetail()
		}
	},
	methods: {
		// 加载用户详情
		async loadUserDetail() {
			try {
				console.log('开始加载用户详情，用户ID：', this.userId)
				uni.showLoading({
					title: '加载中...'
				})
				
				const res = await uniCloud.callFunction({
					name: 'getUserDetail',
					data: { 
						userId: this.userId,
						action: 'edit'
					}
				})
				
				console.log('获取用户详情结果：', res)
				
				if (res.result.code === 0) {
					// 保留原有的密码字段
					this.userInfo = {
						...res.result.data,
						password: res.result.data.password || '' // 显示原始密码
					}
					console.log('用户信息已更新：', this.userInfo)
				} else {
					console.error('获取用户详情失败：', res.result.msg)
					uni.showToast({
						title: res.result.msg || '加载失败',
						icon: 'none'
					})
				}
			} catch (error) {
				console.error('加载用户详情失败', error)
				uni.showToast({
					title: '加载失败',
					icon: 'none'
				})
			} finally {
				uni.hideLoading()
			}
		},
		
		// 选择头像
		async chooseAvatar() {
			try {
				const res = await uni.chooseImage({
					count: 1,
					sizeType: ['compressed'],
					sourceType: ['album', 'camera']
				})
				
				if (res.tempFilePaths && res.tempFilePaths.length > 0) {
					// 上传图片到云存储
					const uploadRes = await uniCloud.uploadFile({
						filePath: res.tempFilePaths[0],
						cloudPath: `avatar/${Date.now()}.jpg`
					})
					
					this.userInfo.avatar = uploadRes.fileID
				}
			} catch (error) {
				console.error('选择头像失败', error)
				uni.showToast({
					title: '选择头像失败',
					icon: 'none'
				})
			}
		},
		
		// 提交表单
		async handleSubmit() {
			// 表单验证
			if (!this.userInfo.username) {
				uni.showToast({
					title: '请输入用户名',
					icon: 'none'
				})
				return
			}
			
			if (!this.userInfo.nickname) {
				uni.showToast({
					title: '请输入昵称',
					icon: 'none'
				})
				return
			}
			
			if (!this.userInfo.mobile) {
				uni.showToast({
					title: '请输入手机号',
					icon: 'none'
				})
				return
			}
			
			if (!/^1[3-9]\d{9}$/.test(this.userInfo.mobile)) {
				uni.showToast({
					title: '请输入正确的手机号',
					icon: 'none'
				})
				return
			}
			
			// 如果是新增用户，需要验证密码
			if (!this.userId && !this.userInfo.password) {
				uni.showToast({
					title: '请输入密码',
					icon: 'none'
				})
				return
			}
			
			try {
				uni.showLoading({
					title: '保存中...'
				})
				
				// 准备要保存的用户信息
				const saveData = {
					...this.userInfo,
					// 如果密码没有修改，则使用原始密码
					password: this.userInfo.password || this.userInfo.originalPassword
				}
				delete saveData.originalPassword
				
				const res = await uniCloud.callFunction({
					name: this.userId ? 'updateUser' : 'addUser',
					data: {
						userId: this.userId,
						userInfo: saveData
					}
				})
				
				if (res.result.code === 0) {
					uni.showToast({
						title: '保存成功',
						icon: 'success'
					})
					setTimeout(() => {
						uni.navigateBack()
					}, 1500)
				} else {
					uni.showToast({
						title: res.result.msg || '保存失败',
						icon: 'none'
					})
				}
			} catch (error) {
				console.error('保存用户失败', error)
				uni.showToast({
					title: '保存失败',
					icon: 'none'
				})
			} finally {
				uni.hideLoading()
			}
		}
	}
}
</script>

<style>
.user-edit {
	min-height: 100vh;
	background-color: #f8f9fc;
	padding-bottom: 120rpx;
}

.section {
	background-color: #fff;
	margin-bottom: 20rpx;
	padding: 30rpx;
}

.section-title {
	font-size: 32rpx;
	font-weight: bold;
	color: #333;
	margin-bottom: 30rpx;
}

.form-item {
	margin-bottom: 30rpx;
}

.form-item .label {
	display: block;
	font-size: 28rpx;
	color: #666;
	margin-bottom: 10rpx;
}

.input {
	width: 100%;
	height: 80rpx;
	background-color: #f5f5f5;
	border-radius: 8rpx;
	padding: 0 20rpx;
	font-size: 28rpx;
}

.upload-box {
	width: 200rpx;
	height: 200rpx;
	background-color: #f5f5f5;
	border-radius: 8rpx;
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
}

.preview-image {
	width: 100%;
	height: 100%;
	border-radius: 8rpx;
}

.upload-placeholder {
	display: flex;
	flex-direction: column;
	align-items: center;
	color: #999;
}

.upload-placeholder .iconfont {
	font-size: 60rpx;
	margin-bottom: 10rpx;
}

.submit-btn {
	position: fixed;
	bottom: 0;
	left: 0;
	right: 0;
	height: 100rpx;
	line-height: 100rpx;
	text-align: center;
	background-color: #4a6ee0;
	color: #fff;
	font-size: 32rpx;
}

/* 图标字体 */
@font-face {
	font-family: "iconfont";
	src: url('//at.alicdn.com/t/font_3456789_abcdef.woff2') format('woff2');
}

.iconfont {
	font-family: "iconfont" !important;
	font-style: normal;
	-webkit-font-smoothing: antialiased;
	-moz-osx-font-smoothing: grayscale;
}

.icon-camera:before {
	content: "\e7d7";
}
</style> 